import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { GrayLight4, Blue } from 'style/Color';
import styled from 'styled-components';
import { FaSearch } from 'react-icons/fa';

const Root = styled.div`
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
`;

const Input = styled.input`
  border: 1px solid ${GrayLight4};
  border-radius: 3px 3px 3px 3px;
  box-sizing: border-box;
  padding: 0 24px 0 6px;
  position: relative;
  min-height: 28px;
  font-size: 12px;
  width: 100%;
`;

const Glass = styled.div`
  transition: color 0.3s ease-in-out;
  color: ${props => (props.active ? Blue : GrayLight4)};
  position: absolute;
  cursor: pointer;
  height: 16px;
  right: 6px;
  width: 16px;
  top: 6px;
`;

class Search extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: props.query
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = () => {
      const { content } = this.state;
      this.props.onSearch(content);
    };
    this.handleEnterKey = e => {
      if (e.nativeEvent.keyCode === 13) {
        this.handleSubmit();
      }
    };
  }

  handleChange(event) {
    this.setState({ content: event.target.value });
  }

  render() {
    const { content } = this.state;
    return (
      <Root>
        <Input
          placeholder={this.props.placeholder}
          type={this.props.type}
          onChange={this.handleChange}
          defaultValue={this.props.query}
          onKeyPress={this.handleEnterKey}
        />
        <Glass onClick={this.handleSubmit} active={content.length > 0}>
          <FaSearch />
        </Glass>
      </Root>
    );
  }
}

Search.defaultProps = {
  placeholder: '',
  type: 'text',
  query: ''
};

Search.propTypes = {
  placeholder: PropTypes.string,
  type: PropTypes.string,
  query: PropTypes.string,
  onSearch: PropTypes.func.isRequired
};

export default Search;
